<script setup lang="ts">
// 获取页面参数
import { ref } from 'vue'
import areaList from '@/utils/area2.json'
import {
  getMemberAddressByIdAPI,
  postMemberAddressAPI,
  putMemberAddressByIdAPI,
} from '@/services/address_api'
import { onLoad } from '@dcloudio/uni-app'

const query = defineProps<{
  id?: string
}>()
// const areaList = ref(area)
// 动态设置标题
uni.setNavigationBarTitle({ title: query.id ? '修改地址' : '新建地址' })

// 表单数据
const form = ref({
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})
// 定义校验规则
const rules = ref({
  receiver: [{ required: true, message: '请输入收货人姓名', trigger: ['blur', 'change'] }],
  contact: [
    { required: true, message: '请输入联系方式', trigger: ['blur', 'change'] },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      transform(value: string | number) {
        return String(value)
      },
      trigger: ['change'],
    },
  ],
  countyCode: [{ required: true, message: '请选择所在地区', trigger: ['change'] }],
  address: [{ required: true, message: '请选择详细地址', trigger: ['blur', 'change'] }],
})
// 收集所在地区
const onRegionChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 省市区(前端展示)
  form.value.fullLocation = ev.detail.value.join(' ')
  // 省市区(后端参数)
  const [provinceCode, cityCode, countyCode] = ev.detail.code!
  // 合并数据
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}

// 收集是否默认收货地址
const onSwitchChange = (value: number) => {
  form.value.isDefault = value
}
// 获取收货地址详情数据

// 表单组件实例
const formRef = ref<UniHelper.UniFormsInstance>()
// 提交表单
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value?.validate?.()
    if (query.id) {
      // 修改地址请求
      await putMemberAddressByIdAPI(query.id, form.value)
    } else {
      // 新建地址请求
      await postMemberAddressAPI(form.value)
    }
    // 成功提示
    await uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 400)
  } catch (err) {
    await uni.showToast({ icon: 'error', title: '请填写完整信息' })
  }
}

const getMemberAddressByIdData = async () => {
  // 有 id 才调用接口
  if (query.id) {
    // 发送请求
    const res = await getMemberAddressByIdAPI(query.id)
    // 把数据合并到表单中
    Object.assign(form.value, res.result)
  }
}
// 页面加载
onLoad(() => {
  getMemberAddressByIdData()
})
const areaH5Picker = ref()
// #ifdef H5 || APP-PLUS
interface areaItem {
  value: string
  text: string
}
const onCityChange = (ev: { detail: { value: areaItem[] } }) => {
  console.log(ev)
  // 省市区(前端展示)
  form.value.fullLocation = ev.detail.value.map((item) => item.text).join('/')
  // 省市区(后端参数)
  const [provinceObj, cityObj, countyObj] = ev.detail.value
  // 合并数据
  form.value = Object.assign(form.value, {
    provinceCode: provinceObj.value,
    cityCode: cityObj.value,
    countyCode: countyObj.value,
  })
}
const showareaPicker = () => {
  areaH5Picker.value?.show()
}
// #endif
</script>
<template>
  <view class="content">
    <u-form
      class="cu-form"
      labelWidth="200rpx"
      :rules="rules"
      :model="form"
      ref="formRef"
      labelPosition="left"
    >
      <!-- 表单内容 -->
      <u-form-item :borderBottom="true" name="receiver" label="收货人" prop="receiver" required>
        <up-input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </u-form-item>
      <u-form-item :borderBottom="true" label="联系方式" prop="contact" required>
        <up-input
          class="input"
          placeholder="请填写收货人手机号码"
          :maxlength="11"
          v-model="form.contact"
        />
      </u-form-item>
      <u-form-item :borderBottom="true" label="所在地区" required prop="countyCode">
        <!-- #ifdef MP-WEIXIN -->
        <picker
          @change="onRegionChange"
          class="picker"
          mode="region"
          :value="form.fullLocation.split(' ')"
        >
          <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- #endif -->

        <!-- #ifdef H5 || APP-PLUS -->
        <!--离线数据-->
        <uni-data-picker
          placeholder="请选择地址"
          popup-title="请选择城市"
          :localdata="areaList"
          :step-searh="true"
          ref="areaH5Picker"
          @change="onCityChange"
          :clear-icon="false"
          :map="{ text: 'name', value: 'code' }"
          ellipsis
          v-model="form.countyCode"
        >
          <view @click="showareaPicker" class="u-flex">
            <text class="u-flex-1"> {{ form.fullLocation }} </text>
            <view class="selected-icon"></view>
          </view>
        </uni-data-picker>
        <!--在线/需要开通阿里云数据库-->
        <!-- <uni-data-picker
          placeholder="请选择地址"
          popup-title="请选择城市"
          collection="opendb-city-china"
          field="code as value, name as text"
          orderby="value asc"
          :step-searh="false"
          self-field="code"
          parent-field="parent_code"
          @change="onCityChange"
          :clear-icon="false"
          v-model="form.countyCode"
        />-->
        <!-- #endif -->
      </u-form-item>
      <u-form-item :borderBottom="true" label="详细地址" prop="address" required>
        <up-input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </u-form-item>
      <u-form-item :borderBottom="true" label="设为默认地址" prop="isDefault">
        <u-switch
          size="32"
          activeColor="#27ba9b"
          :activeValue="1"
          :inactiveValue="0"
          v-model="form.isDefault"
          @change="onSwitchChange"
        ></u-switch>
      </u-form-item>
    </u-form>
  </view>
  <!-- 提交按钮 -->
  <button @tap="onSubmit" class="button">保存并使用</button>
</template>

<style lang="scss">
// 深度选择器修改 uni-data-picker 组件样式
:deep(.selected-area) {
  flex: 0 1 auto;
  height: auto;
}
.content :deep(.u-form-item__body) {
  padding: 12rpx !important;
  .u-input {
    padding-bottom: 0 !important;
    padding-top: 0 !important;
  }
  .input-value-border {
    border: none !important;
  }
  /*数据选择框边框及换行溢出*/
  .uni-data-tree-input .selected-list {
    //flex-wrap: wrap !important;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    word-break: break-word;
    -webkit-line-clamp: 2;
    -webkit-box-orient: horizontal;
  }
  /*弹出框文字居左*/
  .uni-data-tree-dialog {
    .selected-item {
      text-align: left !important;
    }
  }
}
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: $my-primary-color;
}
</style>
